package org.sam.swing.renderer;

import java.awt.Component;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JLabel;
import javax.swing.JList;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.sam.swing.utils.ReflectUtil;

/**
 * 实体字段renderer
 * 
 * @author sam
 *
 */
public class EntityFileldCellRenderer extends DefaultListCellRenderer {

	private static final long serialVersionUID = 3069084911751793829L;

	/**
	 * 字段名称
	 */
	private String fieldName;

	/**
	 * 字段名称
	 */
	public String getFieldName() {
		return fieldName;
	}

	/**
	 * 字段名称
	 */
	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

	/**
	 * 实体字段renderer
	 */
	public EntityFileldCellRenderer() {
		super();
	}

	/**
	 * 实体字段renderer
	 * 
	 * @param fieldName
	 *            实体字段
	 */
	public EntityFileldCellRenderer(String fieldName) {
		this();
		this.setFieldName(fieldName);
	}

	/**
	 * 重写的方法
	 */
	@Override
	public Component getListCellRendererComponent(JList<? extends Object> list, Object value, int index,
			boolean isSelected, boolean cellHasFocus) {
		JLabel c = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
		if (!StringUtils.isEmpty(fieldName)) {
			if (value != null) {
				Pair<Boolean, Object> result = ReflectUtil.invokeGetMethod(value, fieldName);
				if (result.getKey()){
					c.setText(result.getValue().toString());
				}
			}
		}
		return c;
	}

}
